<template>
  <div>
    <el-form label-width="80px" ref="form">
      <el-form-item label="SPU名称">
        <el-input placeholder="SPU的名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option :label="tm.tmName" :value="tm.id" v-for="tm in tradeMarkList" :key="tm.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input placeholder="描述" type="textarea" rows="4" v-model="spu.description"></el-input>
      </el-form-item>
      <!-- 照片墻 -->
      <el-form-item label="spu的图片">
        <!-- 
          list-type文件列表的类型 
          on-preview:图片预览时触发
          action:图片上传地址
          on-remove:当删除图片的时候回触发
          file-list:照片墙的图片数据列表 数据对象必须要有name与url字段
        -->
        <el-upload action="/dev-api/admin/product/fileUpload" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :file-list="spuImgList" :on-success="handlerSuccess">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <!-- 销售属性 -->
      <el-form-item label="销售属性">
        <el-select :placeholder="`还有${upSelectSaleAttr.length}未选择`" v-model="attrIdAndAttrName">
          <el-option :label="unSelect.name" :value="`${unSelect.id}:${unSelect.name}`" v-for="unSelect in upSelectSaleAttr" :key="unSelect.id"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-plus" :disabled="!attrIdAndAttrName" @click="addSaileAttr">添加销售属性</el-button>
        <!-- 展示spu当前自己的销售属性 -->
        <el-table border :data="spu.spuSaleAttrList" style="width:100%">
          <el-table-column type="index" align="center" label="序号" width="80px">

          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性值名称列表" width="width">
            <template slot-scope="{row,$index}">
              <!-- el-tag展示属性值列表 -->
              <el-tag :key="tag.id" v-for="(tag,index) in row.spuSaleAttrValueList" closable :disable-transitions="false" @close="row.spuSaleAttrValueList.splice(index,1)">
                {{tag.saleAttrValueName}}
              </el-tag>
              <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm_keyup($event)" @blur="handleInputConfirm(row)">
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="addSaleAttrValue(row)">添加</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{row,$index}">
              <el-button type="danger" icon="el-iconldelete" @click="deleteAttr($index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdataSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>
import api from '@/api'

export default {
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      // spu信息属初始化时是一个空对象 在修改spu属性时 会向服务器发请求 返回spu信息 在修改时可以利用服务器返回的这个对象收集最新的数据提交给服务器
      // 如果是spu添加的时候 也是收集spu数据提交给服务器
      spu: {
        category3Id: 0,
        description: '',
        tmId: '',
        spuName: '',
        spuImageList: [
          /*  {
            id: 0,
            imgName: 'string',
            imgUrl: 'string',
            spuId: 0
          } */
        ],
        // 销售属性
        spuSaleAttrList: [
          {
            baseSaleAttrId: 0,
            saleAttrName: 'string',
            spuId: 0,
            // 销售属性值
            spuSaleAttrValueList: [
              /* {
              baseSaleAttrId: 0,
              id: 0,
              isChecked: 'string',
              saleAttrName: 'string',
              saleAttrValueName: 'string',
              spuId: 0
            } */
            ]
          }
        ]
        // 未选择销售属性id
      },
      // 品牌信息
      tradeMarkList: [],
      spuImgList: [],
      // 整个平台的销售属性
      saleAttrList: [],
      attrIdAndAttrName: ''
    }
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    // 照片墙图片预览的回调
    handlePictureCardPreview(file) {
      // 将预览的图片地址赋值给该属性
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 照片墙删除图片
    // file:当前删除的图跑
    // fileList：剩余的其他图片
    handleRemove(file, fileList) {
      // 对于已有的数据 会带有url 与 name字段 用于显示照片墙
      // 对于提交到服务器的数据而言 是不需要name与url字段的
      this.spuImageList = fileList
    },
    // 照片墙图片上传图片成功的图片
    // response：图片上传成功的回调
    handlerSuccess(response, file, fileList) {
      console.log(response, file, fileList)
      this.spuImgList = fileList
    },
    // 编辑初始化spu数据
    async initSpuData(spu) {
      console.log(spu)
      // spu商品信息
      let spuResult = await this.$API.spu.reqSpu(spu.id)
      if (spuResult.code === 200) {
        this.spu = spuResult.data
      }
      let tradeMarkResult = await this.$API.spu.reqTrademarkList()
      if (tradeMarkResult.code === 200) {
        this.tradeMarkList = tradeMarkResult.data
      }
      // spu图片信息
      let spuImgResult = await this.$API.spu.reqSpuImageLIST(spu.id)
      if (spuImgResult.code === 200) {
        let result = spuImgResult.data
        result.forEach(item => {
          item.name = item.imgName
          item.url = item.imgUrl
        })
        this.spuImgList = result
      }
      // 获取品他所有销售属性
      let saleResult = await this.$API.spu.reqBaseSaleAttrList()
      if (saleResult.code === 200) {
        this.saleAttrList = saleResult.data
      }
    },
    // 添加销售属性
    addSaileAttr() {
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(':')
      let newSaleAttr = { baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [] }
      this.spu.spuSaleAttrList.push(newSaleAttr)
      this.attrIdAndAttrName = ''
    },
    // 添加销售属性值
    addSaleAttrValue(row) {
      this.$set(row, 'inputVisible', true)
      // row.inputVisible=true
      this.$set(row, 'inputValue', '')
    },
    // 添加销售属性input失去焦点事件
    handleInputConfirm(row) {
      row.inputVisible = false
      const { baseSaleAttrId, inputValue } = row
      let newSaleAttrValue = { baseSaleAttrId, saleAttrValueName: inputValue }
      if (inputValue.trim() === '') return this.$message('属性值不能为空')
      // 重复返回false 没有重读返回true
      let result = row.spuSaleAttrValueList.every(item => item.saleAttrValueName !== inputValue)
      if (!result) return this.$message('添加的属性值重复！')
      row.spuSaleAttrValueList.push(newSaleAttrValue)
    },
    // 添加销售属性值input kyyup键入
    handleInputConfirm_keyup($event) {
      $event.target.blur()
    },
    // 删除销售属性
    deleteAttr($index) {
      this.$message({
        message: '删除销售属性值成',
        type: 'success'
      })
      setTimeout(() => {
        this.spu.spuSaleAttrList.splice($index, 1)
      }, 1000)
    },
    // 保存按钮
    async addOrUpdataSpu() {
      // 整理照片墙 图片参数需要携带imgName与imgUrl字段
      // console.log(this.spuImgList)
      this.spu.spuImageList = this.spuImgList.map(item => ({
        imgName: item.name,
        imgUrl: (item.response && item.response.data) || item.url
      }))
      let result = await this.$API.spu.reqAddOrUpdataSpu(this.spu)
      if (result.code === 200) {
        this.$message({
          type: 'success',
          message: '保存成功'
        })
        this.$emit('changeScene', { scence: 0, flag: this.spu.id ? '修改' : '添加' })
      }
      Object.assign(this._data, this.$options.data())
    },
    // 添加spu按钮的回调
    async addSpuData(category3Id) {
      this.spu.category3Id = category3Id
      let tradeMarkResult = await this.$API.spu.reqTrademarkList()
      if (tradeMarkResult.code === 200) {
        this.tradeMarkList = tradeMarkResult.data
      }
      let saleResult = await this.$API.spu.reqBaseSaleAttrList()
      if (saleResult.code === 200) {
        this.saleAttrList = saleResult.data
      }
    },
    cancel() {
      this.$emit('changeScene', { scene: 0, flag: '' })
      // 取消按钮时防止数据回显  this.$options当前组件的配置对象 data函数用于返回一个空对象
      Object.assign(this._data, this.$options.data())
    }
  },
  computed: {
    // 计算出还未选择的销售属性
    upSelectSaleAttr() {
      return this.saleAttrList.filter(item => this.spu.spuSaleAttrList.every(item1 => item.name != item1.saleAttrName))
    }
  }
}
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
